"""
邮件配置相关的Pydantic模式定义
"""

from pydantic import BaseModel, validator, EmailStr
from typing import Optional, List, Dict, Any
from datetime import datetime
from enum import Enum


class EncryptionType(str, Enum):
    """加密类型枚举"""
    NONE = "none"
    SSL = "ssl"
    STARTTLS = "starttls"


class EmailConfigCreate(BaseModel):
    """创建邮件配置请求模式"""
    name: str
    smtp_host: str
    smtp_port: int
    username: str
    password: str
    from_email: EmailStr
    from_name: Optional[str] = None
    encryption: EncryptionType = EncryptionType.NONE
    timeout: int = 30
    description: Optional[str] = None
    
    @validator('name')
    def validate_name(cls, v):
        if not v or len(v.strip()) < 2:
            raise ValueError('配置名称至少需要2个字符')
        return v.strip()
    
    @validator('smtp_host')
    def validate_smtp_host(cls, v):
        if not v or len(v.strip()) < 3:
            raise ValueError('SMTP服务器地址不能为空')
        return v.strip()
    
    @validator('smtp_port')
    def validate_smtp_port(cls, v):
        if not 1 <= v <= 65535:
            raise ValueError('端口号必须在1-65535之间')
        return v
    
    @validator('username')
    def validate_username(cls, v):
        if not v or len(v.strip()) < 1:
            raise ValueError('用户名不能为空')
        return v.strip()
    
    @validator('password')
    def validate_password(cls, v):
        if not v or len(v.strip()) < 1:
            raise ValueError('密码不能为空')
        return v
    
    @validator('timeout')
    def validate_timeout(cls, v):
        if not 5 <= v <= 300:
            raise ValueError('超时时间必须在5-300秒之间')
        return v


class EmailConfigUpdate(BaseModel):
    """更新邮件配置请求模式"""
    name: Optional[str] = None
    smtp_host: Optional[str] = None
    smtp_port: Optional[int] = None
    username: Optional[str] = None
    password: Optional[str] = None
    from_email: Optional[EmailStr] = None
    from_name: Optional[str] = None
    encryption: Optional[EncryptionType] = None
    timeout: Optional[int] = None
    description: Optional[str] = None
    
    @validator('name')
    def validate_name(cls, v):
        if v is not None and (not v or len(v.strip()) < 2):
            raise ValueError('配置名称至少需要2个字符')
        return v.strip() if v else v
    
    @validator('smtp_host')
    def validate_smtp_host(cls, v):
        if v is not None and (not v or len(v.strip()) < 3):
            raise ValueError('SMTP服务器地址不能为空')
        return v.strip() if v else v
    
    @validator('smtp_port')
    def validate_smtp_port(cls, v):
        if v is not None and not 1 <= v <= 65535:
            raise ValueError('端口号必须在1-65535之间')
        return v
    
    @validator('username')
    def validate_username(cls, v):
        if v is not None and (not v or len(v.strip()) < 1):
            raise ValueError('用户名不能为空')
        return v.strip() if v else v
    
    @validator('password')
    def validate_password(cls, v):
        if v is not None and (not v or len(v.strip()) < 1):
            raise ValueError('密码不能为空')
        return v
    
    @validator('timeout')
    def validate_timeout(cls, v):
        if v is not None and not 5 <= v <= 300:
            raise ValueError('超时时间必须在5-300秒之间')
        return v


class EmailConfigResponse(BaseModel):
    """邮件配置响应模式"""
    id: int
    name: str
    smtp_host: str
    smtp_port: int
    username: str
    from_email: str
    from_name: Optional[str]
    encryption: EncryptionType
    timeout: int
    description: Optional[str]
    user_id: int
    is_active: bool
    created_at: datetime
    updated_at: datetime
    
    class Config:
        from_attributes = True


class EmailConfigList(BaseModel):
    """邮件配置列表响应模式"""
    items: List[EmailConfigResponse]
    total: int
    page: int
    size: int
    pages: int


class EmailConfigTest(BaseModel):
    """邮件配置测试请求模式"""
    smtp_host: str
    smtp_port: int
    username: str
    password: str
    from_email: EmailStr
    encryption: EncryptionType = EncryptionType.NONE
    timeout: int = 30
    test_email: Optional[EmailStr] = None  # 测试邮件接收地址
    
    @validator('smtp_host')
    def validate_smtp_host(cls, v):
        if not v or len(v.strip()) < 3:
            raise ValueError('SMTP服务器地址不能为空')
        return v.strip()
    
    @validator('smtp_port')
    def validate_smtp_port(cls, v):
        if not 1 <= v <= 65535:
            raise ValueError('端口号必须在1-65535之间')
        return v
    
    @validator('timeout')
    def validate_timeout(cls, v):
        if not 5 <= v <= 300:
            raise ValueError('超时时间必须在5-300秒之间')
        return v


class EmailConfigTestResponse(BaseModel):
    """邮件配置测试响应模式"""
    success: bool
    message: str
    details: Optional[Dict[str, Any]] = None
    test_email_sent: bool = False


class EmailConfigStatistics(BaseModel):
    """邮件配置统计信息"""
    total: int
    active: int
    by_encryption: Dict[str, int]
    recent_added: int  # 最近7天新增


class EmailSendTest(BaseModel):
    """邮件发送测试请求模式"""
    config_id: int
    to_email: EmailStr
    subject: str = "邮件配置测试"
    content: str = "这是一封测试邮件，用于验证邮件配置是否正常工作。"
    
    @validator('subject')
    def validate_subject(cls, v):
        if not v or len(v.strip()) < 1:
            raise ValueError('邮件主题不能为空')
        return v.strip()
    
    @validator('content')
    def validate_content(cls, v):
        if not v or len(v.strip()) < 1:
            raise ValueError('邮件内容不能为空')
        return v.strip()


class EmailSendTestResponse(BaseModel):
    """邮件发送测试响应模式"""
    success: bool
    message: str
    message_id: Optional[str] = None
    details: Optional[Dict[str, Any]] = None
